<?php
namespace app\common\model;
use think\Model;
use think\facade\Db;
use think\model\concern\SoftDelete;

class Store extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    protected $type = [
        'exp_time'     => 'timestamp:Y-m-d',
    ];

    public function getExpDayAttr($value,$data)
    {
        //过期日期
        $exp_time = $data['exp_time'];
        //当前时间
        $times = $exp_time-time();
        //计算时间戳
        $day = $times/86400;
        return intval($day);
    }

    /**
     * 关联日志表
     * @return \think\model\relation\HasMany
     */
    public function log()
    {
        return $this->hasMany(StoreLog::class, 'store_id', 'id');
    }

    /**
     * 关联套餐表
     * @return \think\model\relation\BelongsTo
     */
    public function taocan()
    {
        return $this->belongsTo(Taocan::class, 'taocan', 'id')->bind(['taocan_name'=>'name']);
    }

    /**
     * 创建商户
     * @param $param
     * @return bool
     */
    static function create_store($param)
    {
        // 启动事务
        Db::startTrans();
        try {
            //创建商户
            $store = self::create($param);
            if($store == false){
                Db::rollback();
                return jsondata(1,"创建商户失败");
            }
            //创建部门
            $group_param['store_id'] = $store->id;
            $group_param['name'] = "总经理";
            $group_param['status'] = "1";
            $group = StoreGroup::create($group_param);
            if($group == false){
                Db::rollback();
                return jsondata(1,"创建部门失败");
            }
            //创建权限角色
            $group_param['rules'] = Taocan::where('id',$param['taocan'])->value('rules');
            $rule = StoreRule::create($group_param);
            if($rule == false){
                Db::rollback();
                return jsondata(1,"创建角色失败");
            }
            //创建用户
            $adduser['store_id'] = $store->id;
            $adduser['name'] = $param['contact'];
            $adduser['mobile'] = $param['mobile'];
            $adduser['password'] = $param['password'];
            $adduser['status'] = "1";
            $adduser['group_id'] = $group->id;
            $adduser['rule_id'] = $rule->id;
            $user = User::create($adduser);
            if($user == false){
                Db::rollback();
                return jsondata(1,"创建用户失败");
            }
            //更新管理员
            self::where('id',$store->id)->update(['admin_id'=>$user->id]);
            Db::commit();
            return jsondata(0,"操作成功");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return jsondata(1,$e->getMessage());
        }

    }

}